#import "FishBrain.h"
#import "RotImage.h"
#ifndef NS3x
#import "Thinker.h"
#else
#import "Thinker3.h"
#endif

#import <libc.h>

@implementation FishBrain


- changeXDirection
{
	direction = direction ^ 
		(((direction & RIGHT) == RIGHT) ?  RIGHT : LEFT);
	xspeed = (float)(random() % MAX_X_SPEED) / 10.0 + .1;
	[body flip:HORIZONTAL];
	return self;
}

- changeYDirection
{
	direction = direction ^ (((direction & UP) == UP) ? UP : DOWN);
 	yspeed = (float)(random() % MAX_Y_SPEED) / 10.0 + .1;
	return self;
}

-init:(NXSize *)drawingSize fishSize:(NXSize *)mysize owner:mybody
{

	body = mybody;
	WIDTH = mysize->width;
	HEIGHT = mysize->height;

	sizeOfAquar = *drawingSize;

	srandom(currentTimeInMs());

	xspeed = (float)(random() % MAX_X_SPEED) / 10.0 + .1;
	yspeed = (float)(random() % MAX_Y_SPEED) / 10.0 + .1;

	xpos = random() % (int)(sizeOfAquar.width-WIDTH);
	ypos = random() % (int)(sizeOfAquar.height-HEIGHT);


	direction = direction ^ (random() % 2) ? RIGHT : LEFT;
	direction = direction ^ (random() % 2) ? UP : DOWN;
	
	if ((direction & LEFT) == LEFT) [self changeXDirection];

	return self;
}

-(float)getXPos 
{
	if ((direction & LEFT) == LEFT) {
		if (xpos < 0.0) {
			xpos = 0.0;
			[self changeXDirection];
			return (xpos += xspeed);
		} else {
			return (xpos -= xspeed);
		}
	} else {
		if (xpos > (sizeOfAquar.width - (WIDTH + (MAX_X_SPEED/2)))) {
			xpos = sizeOfAquar.width - (WIDTH + (MAX_X_SPEED/2));
			[self changeXDirection];
			return (xpos -= xspeed);
		} else {
			return (xpos += xspeed);
		}
	}
	return xpos;
}

-(float)getYPos
{
	if ((direction & DOWN) == DOWN) {
		if (ypos < 0.0) {
			ypos = 0.0;
			[self changeYDirection];
		} else {
			return (ypos -= yspeed);
		}
	} else {
		if (ypos > (sizeOfAquar.height - (HEIGHT + (MAX_Y_SPEED/2)))) {
			ypos = sizeOfAquar.height - (HEIGHT + (MAX_Y_SPEED/2));
			[self changeYDirection];
		} else {
			return (ypos += yspeed);
		}
	}
	return ypos;
}

-(float)getXSpeed 
{
	return xspeed;
}

-(float)getYSpeed
{
	return yspeed;
}

-(float)getAngle 
{
	return angle;
}

-(int)getDirection 
{
	return direction;
}

-viewDidResize:(NXSize *)newSize
{
	sizeOfAquar = *newSize;
	return self;
}

-(NXPoint)getCurrentPoint 
{
	NXPoint tmp;

	tmp.x = xpos;
	tmp.y = ypos;
	return tmp;
}

@end
